/**
 * Created by zwxu on 2017/4/5.
 */

$(function() {
	initTable();
	initDialog();
	initQuery();
	
	$("#upload_btn").on("click", function() {
		openRoleDialog("add", null);
	});

	$("#role_form").validate({
		rules : {
			name : "required"
		},
		messages : {
			name : "请输入角色名称"
		},
		submitHandler : function() {
			var id = $("#dialog_id").val();
			if(id == null || id == ""){
				roleDialogAdd();
			}else{
				roleDialogEdit();
			}	
		}
	});
	
})

function openRoleDialog(type, data) {
	if (!$.isEmptyObject(type) && type == "add") {
		$("#role_dialog").dialog('option', 'title', "新增角色");
		$("#role_dialog").dialog({
			buttons : {
				"取消" : function() {
					$(this).dialog("close");
				}
			}
		});
	} else {
		$("#role_dialog").dialog('option', 'title', "编辑角色");
		$("#role_dialog").dialog({
			buttons : {
				"取消" : function() {
					$(this).dialog("close");
				}
			}
		});
		$("#dialog_id").val(data.id);
		$("#dialog_name").val(data.name);
	}
	$("#role_dialog").dialog('open');
	
}

function initQuery() {
	$("#role_query_btn").click(function() {
		table.fnDraw();
	});
}
function initDialog() {
	$("#role_dialog").dialog({
		autoOpen : false,
		resizable : false,
		height : 500,
		width : 500,
		modal : true,
		close : function(e, u) {
			$(this).find(".text-error").remove();
			$(this).find(":text,:hidden,select").val("");
			$(this).find("select > option").remove();
		}
	});
	
	$("#role_menu_dialog").dialog({
		autoOpen : false,
		resizable : false,
		height : 500,
		width : 500,
		modal : true,
		close : function(e, u) {
			$(this).find(".text-error").remove();
			$(this).find(":text,:hidden,select").val("");
			$(this).find("select > option").remove();
		}
	});
}


function initTable() {
	table = $('#dynamic-table')
			.dataTable(
					{
						"bInfo" : true,
						"bServerSide" : true,
						"bPaginate" : true,
						"bFilter" : false,
						"aaSorting" : [],
						"bProcessing" : false,
						"bLengthChange" : true,
						"iDisplayLength" : 10,
						"aLengthMenu" : [ [ 10, 20, 50, 500, 1000 ],
								[ 10, 20, 50, 500, 1000 ] ],
						"sPaginationType" : "full_numbers",
						"bStateSave" : false,
						"bAutoWidth" : false,
						"sDom" : '<"top"f>r<"datatable-scroll"t><"datatable-bottom"lip>',
						"oLanguage" : {
							"sLengthMenu" : "<div style='float:left;margin-left:0px;'>_MENU_</div>",
							"sZeroRecords" : "抱歉， 没有找到",
							"sInfo" : "第 _PAGE_ 页 ( 总共 _PAGES_ 页 )",
							"sInfoEmpty" : "共 0 条数据/共 0 页！",
							"sInfoFiltered" : "(filtered from _MAX_ total records)",
							"sProcessing" : "加载中...",

							oPaginate : {
								sPrevious : "上一页",
								sNext : "下一页",
								sFirst : "首页",
								sLast : "尾页"
							}
						},
						"sAjaxSource" : ctx + "/web/role/list",
						"sServerMethod" : "POST",
						"sSearch" : "搜索",
						// 服务器端，数据回调处理
						"fnServerData" : function(sSource, aDataSet, fnCallback) {

							$.ajax({
								"dataType" : 'json',
								"type" : "POST",
								"url" : sSource,
								"data" : aDataSet,
								"success" : fnCallback
							});
						},
						"fnServerParams" : function(aoData) {

							aoData.push({
								"name" : "name",
								"value" : $("#name").val()
							});
						},
						"fnDrawCallback" : function(oSettings) {
							// console.log( 'DataTables 重绘了' +
							// oSettings.aoServerParams.name);
						},
						"aoColumnDefs" : [
								{
									"render" : function(data, type, row) {
										var val = row[2];
										return "<a href='javascript:;' onclick='relativeMenu({0})'>关联菜单</a>"
												.format(val);
									},
									"targets" : 2
								},
								{
									"render" : function(data, type, row) {
										var val = row[3];
										return "<a href='javascript:;' onclick='editRole({0})'>编辑</a>"
												.format(val);
									},
									"targets" : 3
								},
								{
									"render" : function(data, type, row) {
										var val = row[4];
										return "<a href='javascript:;' onclick='deleteRole({0})'>删除</a>"
												.format(val);
									},
									"targets" : 4
								} ],
						"aoColumns" : [ {
							"bSortable" : false
						}, {
							sName : "id",
							"bSortable" : true
						}, {
							sName : "name"
						} ]
					});
	var tableSetings = $('#dynamic-table').dataTable().fnSettings()
}
function relativeRoleMenu(){
	var roleId = $("#dialog_id").val();
	 var treeObj=$.fn.zTree.getZTreeObj("treeDemo"),
     checkedNodes=treeObj.getCheckedNodes(true),
     v1="";
     for(var i=0;i<checkedNodes.length;i++){
	     v1+=checkedNodes[i].id + ",";
	     
     }
     //alert(v1.substring(0,v1.length-1)); //获取选中节点的值
     uncheckedNodes=treeObj.getCheckedNodes(false),
     v2="";
     for(var i=0;i<uncheckedNodes.length;i++){
	     v2+=uncheckedNodes[i].id + ",";
	     
     }
     //alert(v2.substring(0,v2.length-1)); //获取选中节点的值
     $.ajax({
 		url : ctx + '/web/role/updateRelativeMenu',
 		type : 'POST',
 		data :{
 			checked:v1.substring(0,v1.length-1),
 			unchecked:v2.substring(0,v2.length-1),
 			roleId:roleId
 		},
 		success : function(data) {
 			if (data) {
 				alert(data);
 			} else {
				table.fnDraw();
			} 
 		}
 	});
}
function relativeMenu(id) {
	var setting = {
			check: {
				enable: true
			},
			data: {
				key: {
					title: "title"
				},
				simpleData: {
					enable: true
				}
			}
		};
	var zNodes = [];
	$.ajax({
		url : ctx + '/web/role/getRelativeMenuList',
		type : 'POST',
		async : false,
		data: {
			roleId:id
		},
		success : function(data) {
			if (data) {
				zNodes = data;
			} 
		}
	});
	$.fn.zTree.init($("#treeDemo"), setting, zNodes);
	$("#dialog_id").val(id);
	$("#role_menu_dialog").dialog("open");
	
	
}
function editRole(id) {
	$.ajax({
		url : ctx + '/web/role/getById',
		type : "post",
		data : {
			id : id
		},
		success : function(data) {
			if (data) {
				openRoleDialog("edit", data);
			} else {
				myalert(null, "获取组件信息失败！");
			}
		},
		error : function() {
			errorPrompt("#com_dialog", "获取组件信息出错");
		}
	});
}
/**
 * @desc 删除接口
 * @arg {long}id
 * @return{string} 返回提示信息
 */
function deleteRole(id) {
	myConfirm('', '确定要删除', function() {
		$.ajax({
			url : ctx + '/web/role/delete',
			type : 'POST',
			data : {
				id : id
			},
			success : function(data) {
				if (data) {
					myalert(null, data);
				} else {
					table.fnDraw();
				}
			}
		});
	});
}
function roleDialogAdd() {
	var param = $("#role_form").serialize();
	console.log(param);
	$.ajax({
		url : ctx + '/web/role/save',
		type : "post",
		data : param,
		success : function(data) {
			if (data) {
				errorPrompt("#role_dialog", data);
			} else {
				$("#role_dialog").dialog("close");
				table.fnDraw();
			}
		},
		error : function() {
			errorPrompt("#role_dialog", "保存出错");
		}
	});
}
/**
 * @desc 编辑组件
 * @return{string} 返回提示信息
 */
function roleDialogEdit() {
	var param = $("#role_form").serialize();
	$.ajax({
		url : ctx + '/web/role/update',
		type : "post",
		data : param,
		success : function(data) {
			if (data) {
				errorPrompt("#role_dialog", data);
			} else {
				$("#role_dialog").dialog("close");
				table.fnDraw();
			}
		},
		error : function() {
			errorPrompt("#role_dialog", "编辑出错");
		}
	});
}

